package com.service.screenWeb.service.impl;

import com.service.config.utils.IdUtil;
import com.service.config.utils.ModelMapperUtil;
import com.service.config.utils.ScanFilesWithRecursionUtils;
import com.service.screenWeb.dao.AssemblyDao;
import com.service.screenWeb.dao.FileUploadDao;
import com.service.screenWeb.dao.ProgrammeInfoDao;
import com.service.screenWeb.dao.VFilePhysicsInfoDao;
import com.service.screenWeb.dto.PosterDto;
import com.service.screenWeb.entity.*;
import com.service.screenWeb.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
public class FileServiceImpl implements FileService {
    @Resource
    private VFilePhysicsInfoDao vFilePhysicsInfoDao;
    @Value("${spring.fileSeverIp}")
    private String systemIp;

    @Value("${spring.fileSeverDomain}")
    private String systemDomain;

    @Value("${spring.imageUrl}")
    private String imageUrl;
    @Resource
    private FileUploadDao dao;

    @Value("${spring.posterUri}")
    private String posterUrl;

    @Value("${spring.defaultBannerUrl}")
    private String[] defaultBannerUrl;

    @Value("${spring.file}")
    private String defaultFilePath;

    /**
     * 上传轮播图片
     * @param file
     * @param assemblyId 组件ID
     * @param programmeId 方案ID
     * @param interval 轮播间隔
     * @throws Exception
     */
    @Override
    public void uploadSlide(MultipartFile file, String assemblyId,String programmeId,String interval) throws Exception {
        Map duplicate = duplicate(file);
        VFilePhysicsInfo vFilePhysicsInfo = ModelMapperUtil.strictMap(duplicate.get("vFilePhysicsInfo"), VFilePhysicsInfo.class);
        Boolean.parseBoolean(duplicate.get("boolean").toString());
        if (assemblyId != null && !assemblyId.equals("")) {
            uploadLogo(vFilePhysicsInfo,file);
        }
        dao.add2AssemblyAndSlide(assemblyId,vFilePhysicsInfo.getId(),programmeId,interval);
    }

    /**
     * 上传海报
     * @param file
     * @param assemblyId 组件ID
     * @param programmeId 方案ID
     * @throws Exception
     */
    @Override
    public void uploadPoster(MultipartFile file, String assemblyId, String programmeId) throws Exception {
        Map duplicate = duplicate(file);
        VFilePhysicsInfo vFilePhysicsInfo = ModelMapperUtil.strictMap(duplicate.get("vFilePhysicsInfo"), VFilePhysicsInfo.class);
        Boolean.parseBoolean(duplicate.get("boolean").toString());
        if (assemblyId != null && !assemblyId.equals("")) {
            uploadLogo(vFilePhysicsInfo,file);
        }
        dao.add2AssemblyAndPoster(assemblyId,vFilePhysicsInfo.getId(),programmeId);
    }

    /**
     * 通过组件ID、方案ID，查询存在的记录条数
     * @param assemblyId
     * @param programmeId
     * @return
     */
    @Override
    public Integer findFileByAssemblyId(String assemblyId,String programmeId)
    {
        return dao.findPosterByAssemblyId(assemblyId,programmeId);
    }

    /**
     * 通过组件ID、方案ID，删除中间表记录
     * @param assemblyId
     * @param programmeId
     * @return
     */
    @Override
    public void deleteFileByAssemblyId(String assemblyId,String programmeId)
    {
        dao.deletePosterByAssemblyId(assemblyId,programmeId);
    }

    /**
     * 获取海报地址
     * @param assemblyId
     * @param programmeId
     * @return
     */
    @Override
    public PosterDto getPosterDic(String assemblyId,String programmeId) {
        PosterDto dto = dao.getPosterDic(assemblyId,programmeId);
        if(null == dto)
        {
            dto=new PosterDto();
            dto.setFilePath(posterUrl);
            return dto;
        }
        String filePath = dto.getFileServerDomain().concat(dto.getFileDicDomain()).concat("/").concat(dto.getFilename());
        dto.setFilePath(filePath);
        return dto;
    }

    /**
     * 获取轮播地址
     * @param assemblyId
     * @param programmeId
     * @return
     */
    @Override
    public List<PosterDto> getSlideInfo(String assemblyId,String programmeId) {
        List<PosterDto> dtos = dao.getSlideInfo(assemblyId,programmeId);
        if(!(dtos.size() > 0))
        {
            for(int i=0;i<3;i++)
            {
                PosterDto dto=new PosterDto();
                dto.setInterval("3");
                dto.setFilePath(defaultFilePath+defaultBannerUrl[i]);
                dtos.add(dto);
            }
            return dtos;
        }
        String filePath="";
        for (PosterDto dto : dtos) {
            filePath=dto.getFileServerDomain().concat(dto.getFileDicDomain()).concat("/").concat(dto.getFilename());
            dto.setFilePath(filePath);
        }
        return dtos;
    }

    @Override
    public void updateInterval(String assemblyId, String programmeId, String interval) {
        dao.updateInterval(assemblyId,programmeId,interval);
    }


    /**
     * 上传文件
     * @param file
     * @param file1
     * @throws IOException
     */
    private void createFile(MultipartFile file,File file1) throws IOException {
        file.transferTo(file1);
    }

    /**
     * 上传文件
     * @param s
     * @return
     */
    private File createFile(String s) {
        File file = new File(s);
        return file;
    }

    /**
     * 上传logo
     * @param vFilePhysicsInfo
     * @throws Exception
     */
    @Transactional
    public void uploadLogo(VFilePhysicsInfo vFilePhysicsInfo, MultipartFile file) throws IOException {
        vFilePhysicsInfo.setFiledic(imageUrl);
        vFilePhysicsInfo.setFiledicdomain("large_screen/logo");
        File file1 = createFile(vFilePhysicsInfo.getFiledic() +"/"+ vFilePhysicsInfo.getFilename());
        createFile(file,file1);
        vFilePhysicsInfo.setFilemd5(ScanFilesWithRecursionUtils.getJdkFileMD5(file1.getPath()));
        vFilePhysicsInfoDao.insert(vFilePhysicsInfo);
    }

    /**
     * 抽取共同代码
     * @param file
     * @return
     * @throws Exception
     */
    private Map duplicate(MultipartFile file) throws Exception {
        Map map = new HashMap();
        VFilePhysicsInfo vFilePhysicsInfo = new VFilePhysicsInfo();
        vFilePhysicsInfo.setId(IdUtil.getStringId());
        String originalFilename = file.getOriginalFilename();// 文件原始名称
        vFilePhysicsInfo.setFilerealname(originalFilename); // 设置文件真实名字
        int i = originalFilename.lastIndexOf(".");
        String substring = originalFilename.substring(i + 1);
        boolean b1 = judgeFileType(substring);// 判断文件类型
        vFilePhysicsInfo.setFiletype(substring);
        vFilePhysicsInfo.setFilename(UUID.randomUUID().toString().replace("-","")+"."+substring); // 对文件重命名
        vFilePhysicsInfo.setFileseverip(systemIp);// 服务器ip
        vFilePhysicsInfo.setFileseverdomain(systemDomain); // 服务器域名
        vFilePhysicsInfo.setStatus("1");
        vFilePhysicsInfo.setDelflag("0");
        map.put("vFilePhysicsInfo",vFilePhysicsInfo);
        map.put("boolean",b1);
        return map;
    }

    /**
     * 判断文件类型
     * @param substring
     * @return
     */
    private boolean judgeFileType(String substring) {
        switch (substring)
        {
            case "gif":
                return true;
            case "jpg":
                return true;
            case "jpeg":
                return true;
            case "png":
                return true;
            case "GIF":
                return true;
            case "JPG":
                return true;
            case "JPEG":
                return true;
            case "PNG":
                return true;
            default:
                return false;
        }
    }

}
